<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <i class="el-icon-info" />
          <span>本月: 社保在缴 公积金在缴</span>
        </template>
        <template #right>
          <el-button type="primary" size="small" @click="$router.push('/import')">导入excel</el-button>
          <el-button type="primary" size="small" @click="exportExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="dialogVisible = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 表格区域 -->
      <el-card style="margin-top: 10px;">
        <el-table :data="list" border>
          <el-table-column label="序号" type="index" width="60"/>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{ row }">
              {{ hireMap[row.formOfEmployment] }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" width="200">
            <template #default="obj">
              {{ formatDate(obj.row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作"  fixed="right" width="200">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="toDetail(row.id)">查看</el-button>
              <el-button type="text" size="small" @click="showAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="remove(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="params.page"
            :page-size="params.size"
            :total="total"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 新增员工弹框 -->
    <add-employee
      :visible="dialogVisible"
      @dialog-close="dialogClose"
      @fetch-employee-list="fetchEmployeeList"
    ></add-employee>
    <!-- 给员工分配角色弹窗 -->
    <el-dialog 
      title="分配角色" 
      :visible="assignRoleVisible" 
      @close="assignRoleClose" 
      @open="assignRoleOpen"
    >
      <!-- 角色多选框 -->
      <el-checkbox-group v-model="checkRoleList">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <!-- 按钮区域 -->
      <template #footer>
        <el-button size="small" @click="assignRoleClose">取消</el-button>
        <el-button type="primary" size="small" @click="submit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// import PageTools from '@/components/PageTools'
import { getEmployeeList, delEmployee, assignRole } from '@/api/employee'
import { getRoleList } from '@/api/setting'
import dayjs from 'dayjs'
import AddEmployee from './components/add-employee.vue'
import { getExportData } from '@/utils/excel'
import { getUserDetailById } from '@/api/user'

export default {
  components: {
    // PageTools
    // 注册新增员工组件
    AddEmployee
  },
  data() {
    return {
      // 员工列表数据
      list: [],
      // 分页参数
      params: {
        page: 1,
        size: 10
      },
      // 聘用形式枚举
      hireMap: {
        1: '正式',
        2: '非正式'
      },
      // 总条数
      total: 0,
      // 控制新增员工弹窗显示与隐藏
      dialogVisible: false,
      // 控制给员工分配角色弹窗显示与隐藏
      assignRoleVisible: false,
      // 某个员工所有的角色列表
      roleList: [],
      // 选中的角色列表
      checkRoleList: [],
      // 员工 id
      employeeId: ''
    }
  },
  created() {
    this.fetchEmployeeList()
  },
  methods: {
    // 获取员工列表数据
    async fetchEmployeeList() {
      const { data: { rows, total } } = await getEmployeeList(this.params)
      // console.log(res)
      // this.list = res.data.rows
      this.list = rows
      this.total = total
    },
    // 日期格式的转换
    formatDate(date) {
      return dayjs(date).format('YYYY-MM-DD')
    },
    // 页码值发生变化时，触发的回调单数
    handleCurrentChange(newPage) {
      // 修改请求参数的页码值
      this.params.page = newPage
      // 重新获取员工列表数据
      this.fetchEmployeeList()
    },
    // 弹窗关闭的回调函数
    dialogClose() {
      this.dialogVisible = false
    },
    // 删除员工
    remove(id) {
      // 询问用户
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 调用接口
        const res = await delEmployee(id)
        // 提示用户
        this.$message.success(res.message)
        // 页数减一
        if (this.list.length === 1 && this.params.page > 1) {
          this.params.page --
        }
        // 刷新列表
        this.fetchEmployeeList()
      }).catch(() => {
      });
    },
    // 导出
    exportExcel() {
      // 动态引入 @/vendor/Export2Excel 包
      import('@/vendor/Export2Excel').then(excel => {
        // excel：是 @/vendor/Export2Excel 包中的 excel 导出模块
        // export_json_to_excel：将 json 数据转换为 excel
        // 表头
        const headerArr = ['姓名', '手机号', '入职日期', '工号', '聘用形式', '部门']
        // 中英对照关系
        const headerRelation = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '工号': 'workNumber',
          '聘用形式': 'formOfEmployment',
          '部门': 'departmentName'
        }
        const twoArr = getExportData(this.list, headerArr, headerRelation)
        console.log(twoArr);

        excel.export_json_to_excel({
          // 表头 header 必填，是一个数组
          header: headerArr, 
          // 表格 body 具体数据，是一个二维数组
          data: twoArr,
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 跳转到员工详情页
    toDetail(id) {
      this.$router.push({
        path: '/employeeDetail',
        query: {
          id
        }
      })
    },
    // 分配角色弹窗关闭
    assignRoleClose() {
      this.assignRoleVisible = false
      this.checkRoleList = []
    },
    // 打开分配角色弹窗
    showAssignRole(id) {
      this.employeeId = id
      this.assignRoleVisible = true
    },
    // 分配角色弹窗打开
    async assignRoleOpen() {
      const res = await getRoleList({
        page: 1,
        pagesize: 100
      })
      this.roleList = res.data.rows
      console.log(res);
      const employeeDetail = await getUserDetailById(this.employeeId)
      this.checkRoleList = employeeDetail.data.roleIds
    },
    // 给员工分配角色
    async submit() {
      const res = await assignRole({
        id: this.employeeId,
        roleIds: this.checkRoleList
      })
      // 提示用户
      this.$message.success(res.message)
      // 关闭弹窗
      this.assignRoleClose()
    }
  }
}
</script>

<style>

</style>